package com.xm;

import java.util.concurrent.ThreadFactory;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * 自定义一个线程工厂类
 * @author xiaoming
 * @date 2021-02-20 17:53
 * @see java.util.concurrent.Executors.DefaultThreadFactory
 */
public class MyThreadFactory implements ThreadFactory {
    private static final AtomicInteger poolNum = new AtomicInteger();
    private final ThreadGroup group;
    private final AtomicInteger threadNum = new AtomicInteger();
    private final String namePrefix;

    public MyThreadFactory() {
        SecurityManager sm = System.getSecurityManager();

        this.group = (sm != null) ? sm.getThreadGroup() : Thread.currentThread().getThreadGroup();

        this.namePrefix = "MyPool-" + poolNum.getAndIncrement() + "-thread-" ;
    }

    public MyThreadFactory(ThreadGroup group) {
        this.group = group;
        this.namePrefix = "MyPool-" + poolNum.getAndIncrement() + "-thread-" ;
    }

    @Override
    public Thread newThread(Runnable r) {
        Thread t = new Thread(group, r,
                namePrefix + threadNum.getAndIncrement(), 0);
        // 设置非守护进程(用户进程)
        if (t.isDaemon()) {
            t.setDaemon(false);
        }
        // 设置优先级
        if (t.getPriority() != Thread.NORM_PRIORITY) {
            t.setPriority(Thread.NORM_PRIORITY);
        }

        return t;
    }
}
